import { getStorage } from '@/utils/auth'
const base_url = 'https://wechatapi.tongzhuangkc.com/kc'
const showToast = (title) => {
  uni.showToast({
    title: title,
    icon: 'none',
  })
}
const request = (obj) => {
  let loadingStatus = true
  setTimeout(() => {
    if (loadingStatus && obj.loading) {
      uni.showLoading({
        title: obj.loadingTitle || '加载中',
        mask: true,
      })
    }
  }, 800) // 800毫秒后如果loadingStatus === false 则表示请求返回了，不显示loading
  return new Promise((resolve, reject) => {
    uni.request({
      url: base_url + obj.url || '',
      method: obj.method || 'POST',
      data: obj.data || {},
      header: {
        token: getStorage('Admin-Token') || '',
        'Content-Type': obj.contentType || 'application/json',
      },
      success: (response) => {
        // 服务器成功返回的回调函数
        const res = response.data
        if (res) {
          if (res.code !== 1) {
            uni.hideLoading()
            loadingStatus = false

            if (res.code === 401) {
              // userStore.resetToken()
              reject(res)
              uni.redirectTo({
                url: '/pages/login/index',
              })
            } else {
              showToast(res.msg)
            }
            resolve(new Error(new Error(res.msg || 'Error')))
          } else {
            resolve(res)
          }
        } else {
          loadingStatus = false
          showToast('[' + res.msg + '] 系统处理失败')
          reject('[' + res.msg + '] 系统处理失败')
        }
      },
      fail: (err) => {
        // 接口调用失败的回调函数
        if (err.errMsg != 'request:fail abort') {
          loadingStatus = false
          showToast('连接超时，请检查您的网络。')
          reject('连接超时，请检查您的网络。')
        }
      },
      complete: () => {
        if (loadingStatus && obj.loading) {
          uni.hideLoading()
          loadingStatus = false
        }
      },
    })
  })
}

export default request
